package com.tron.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;

public class ServerSocketStart {

    private static final HashMap<String,String> hashMap = new HashMap<>();

    static {
        hashMap.put("1", "我是1");
        hashMap.put("2", "我是2");
        hashMap.put("3", "我是三");
    }

    public static void main(String[] args) throws IOException {
        final ServerSocket serverSocket = new ServerSocket(9999);
        while (true) {
            // 检测连接，阻塞。
            final Socket accept = serverSocket.accept();
            System.out.println("====没有连接时我不会打印====");
            System.out.println("域名                 IP           Port");
            System.out.printf("%-20s %-12s %-4s\n",accept.getInetAddress().getHostName(),accept.getInetAddress().getHostAddress(),accept.getPort());
            final AcceptThread acceptThread = new AcceptThread(accept);
            acceptThread.start();
        }
    }

    public static class AcceptThread extends Thread{

        private Socket socket;

        public AcceptThread(Socket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            try(final InputStream inputStream = socket.getInputStream();
                final OutputStream outputStream = socket.getOutputStream()){
                final Scanner scanner = new Scanner(inputStream);
                final PrintWriter printWriter = new PrintWriter(outputStream,true);
                printWriter.println("您好!我是服务器。我可以重复你说的话，不信您可以试试！");
                boolean done = false;
                while (!done && scanner.hasNextLine()) {
                    final String line = scanner.nextLine();
                    System.out.printf("客户说：%s\n",line);
                    final String messageByCode = getMessageByCode(line);
                    System.out.printf("服务器：%s\n",messageByCode);
                    printWriter.println("服务器说: "+ messageByCode);
                    if (line.trim().equals("quit")) {
                        done = true;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getMessageByCode(String code) {
        final String s = hashMap.get(code);
        if (null != s) {
            return s;
        }
        return "我不知道";
    }

}
